<template>
	<view class="container" v-show="tokenShow">
		<!-- 消息列表 -->
		<view class="msg-list">
			<u-swipe-action>
				<view class="item" @click="handleOpenPlatMessage">
					<image src="/static/icon1/54.png" mode="aspectFill"></image>
					<text class='circle' v-if="isNewPlatMsg"></text>
					<view style="width: 100%;">
						<text>平台消息</text>
						<text
							style="width: 91%;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">{{ lastPlatMsg.content.title }}</text>
					</view>
					<text class="time">{{ lastPlatMsgTime }}</text>
				</view>
				<!-- 消息列表 -->
				<view :key="msgUserRange">
					<u-swipe-action-item v-if="conversationList.length>0" v-for="(item, index) in conversationList"
						:key="index" v-show="show1" :options="[{text: '删除',style: {backgroundColor: '#f56c6c'}}]"
						@click="handleDeleteLine(item)">
						<view class="item" @click="toChat(item)">
							<image :src="item.avatar ? imgPath + item.avatar : '/static/icon1/54.png'"
								mode="aspectFill">
							</image>
							<view>
								<text>{{ item.userName }}</text>
								<text
									v-if="item.lastmsg">{{ (item.lastmsg.length < 19 ? item.lastmsg : item.lastmsg.slice(0, 19) + '...') || ''}}</text>
							</view>
							<!-- 未读消息 -->
							<text class='circle' v-if="item.msgsign === 0"></text>
							<text class="time">{{ $u.timeFrom(item.lastmsgTime) }}</text>
						</view>
					</u-swipe-action-item>
				</view>
			</u-swipe-action>
		</view>
	</view>
</template>
<script>
	import sqlite from '@/libs/sqlite/chatSqlite.js'
	import formatDate from '@/libs/time-date.js'
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'
	export default {
		components: {
			uniLoadMore,
		},
		data() {
			return {
				myuid: uni.getStorageSync('userId'), // 自己的uid
				imgPath: uni.getStorageSync('imgPath'),
				lastPlatMsg: {
					content: {
						titleText: ''
					}
				}, //最后一条平台消息
				lastPlatMsgTime: '', //最后一条平台消息时间
				conversationList: [], //对话列表
				requestObj: { //
					pageNum: 1,
					pageSize: 1,
				},
				msgUserRange: (Math.random() * 1000000).toFixed(0),
				userType: uni.getStorageSync('userType'),
				whiteList: [],
				tokenShow: uni.getStorageSync('token'),
				show1: true
			}
		},
		computed: {
			'isNewPlatMsg': function() {
				return this.$store.state.isNewPlatMsg
			},
			'isChatMsg': function() {
				return this.$store.state.isChatMsg
			},
			'isTabBar': function() {
				return this.$store.state.isTabBar
			},
		},
		onLoad() {
			if (!uni.getStorageSync('token')) {
				uni.reLaunch({
					url: '/pages/login/login'
				})
			} else {
				this.getWhiteList()
			}
		},
		onShow() {
			uni.hideTabBar()
			this.getMsgUser()
			uni.$on('newMsg', newMsg => {
				this.getMsgUser()
				let routes = getCurrentPages()
				let curRoute = routes[routes.length - 1].route
				if (curRoute == 'pages/message/message-new' || curRoute == 'pages/message/message') {
					uni.startPullDownRefresh()
				}
			})
			this.get_push_msg_list() //平台消息
			this.$forceUpdate()
		},
		methods: {
			// 用户类型0 雇员，1雇主
			async getWhiteList() {
				let res = await this.$fetch(this.$api.chat_white_list, {
					userType: this.userType
				}, 'POST')
				if (res.code == 401) {
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return
				}
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				this.whiteList = res.data
			},
			async handleDeleteLine(item) {
				sqlite.deleteMsg(item.userId)
				this.conversationList.forEach((value, index, array) => {
					if (value.userId == item.userId) {
						array.splice(index, 1)
					}
				})
			},
			getMsgUser() {
				sqlite.selectMuser().then(userlist => {
					let ulist = [...userlist]
					ulist.forEach((user, i) => {
						sqlite.selectLastMsg({
							toId: this.myuid,
							fromId: user.userId
						}).then(lastmsgs => {
							// console.log('======获取最新一条消息', lastmsgs)
							if (lastmsgs && lastmsgs.length > 0) {
								let lastmsginfo = lastmsgs[0]
								user.lastmsg = (lastmsginfo.msgType === 1 ? lastmsginfo.msg :
									'[非文本消息]')
								user.lastmsgTime = lastmsginfo.createTime
								user.msgsign = lastmsginfo.sign
							}
						})
					})
					this.conversationList = ulist
					console.log('***************', this.conversationList)
					this.msgUserRange = (Math.random() * 1000000).toFixed(0)
					uni.stopPullDownRefresh()
				}).catch(e => {
					console.log('error---', e)
				})
			},
			toChat(row) {
				uni.setStorageSync('isTabBarRed', false)
				this.$store.commit('isNewPlatMsgChange', false)
				uni.removeTabBarBadge({
					index: 2,
					success: (res) => {
						// console.log('成功')
					},
					fail: (err) => {
						// console.log('err', err)
					},
				})
				let userinfo = {
					userId: row.userId,
					userName: row.userName,
					userAvatar: row.avatar
				}
				let tempNewStatus = this.whiteList.indexOf(row.userId) !== -1
				uni.navigateTo({
					url: "/pages/he-chat/HE-chat?jmpType=1&form=" + JSON.stringify(userinfo) + "&stu=" +
						tempNewStatus
				})
			},
			// 获取平台消息列表
			async get_push_msg_list() {
				let res = await this.$fetch(this.$api.get_push_msg_list, this.requestObj, 'POST')
				//console.log(res)
				if (res.total > 0) {
					res.rows[0].content = JSON.parse(res.rows[0].content)
					this.lastPlatMsg = res.rows[0]
					this.lastPlatMsgTime = this.lastPlatMsg.createTime
					let currentTime = formatDate(new Date().getTime())
					let yesterday = formatDate(new Date().setDate(new Date().getDate() - 1))
					if (this.lastPlatMsgTime.slice(0, 11) == currentTime.slice(0, 11)) {
						this.lastPlatMsgTime = this.lastPlatMsgTime.slice(11, 16)
					} else if (this.lastPlatMsgTime.slice(0, 11) == yesterday.slice(0, 11)) {
						this.lastPlatMsgTime = '昨天'
					} else {
						this.lastPlatMsgTime = this.lastPlatMsgTime.slice(0, 11)
					}
				}
				uni.stopPullDownRefresh()
			},
			//打开平台消息页面
			handleOpenPlatMessage() {
				uni.setStorageSync('isTabBarRed', false)
				uni.setStorageSync('isReceiveBarRed', false)
				this.$store.commit('isNewPlatMsgChange', false)
				this.$store.commit('isTabBarChange', false)
				uni.removeTabBarBadge({
					index: 2,
					success: (res) => {
						// console.log('成功')
					},
					fail: (err) => {
						// console.log('err', err)
					},
				})
				uni.navigateTo({
					url: "/pages/platform-message/platform-message"
				})
				// 打开平台消息，是平台消息红点
				// 判断底部消息红点在不在
				// this.getMsgList()
			},
			onNavigationBarButtonTap() {},
			onPullDownRefresh() {
				//监听用户下拉动作，一般用于下拉刷新
				this.getMsgUser()
				this.get_push_msg_list()
			},
		}
	}
</script>
<style lang="less">
	.container {
		position: relative;
		overflow: hidden;

		.msg-list {
			margin-top: 30rpx;

			.item {
				padding: 26rpx 30rpx 24rpx;
				background: #FFFFFF;
				display: flex;
				position: relative;

				&>.icon {
					align-self: center;
					// border: 1px solid #000000;
					margin-left: 20rpx;
					margin-right: 30rpx;
				}

				&>image {
					max-width: 90rpx;
					min-width: 90rpx;
					max-height: 90rpx;
					min-height: 90rpx;
					margin-right: 30rpx;
					border-radius: 50%;
					background-color: #f3f3f3;
				}

				&>.circle {
					position: absolute;
					top: 30rpx;
					left: 110rpx;
					background-color: #FF4500;
					font-size: 12px;
					color: #FFFFFF;
					width: 20rpx;
					height: 20rpx;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				&>view {
					display: flex;
					flex-direction: column;

					text:first-child {
						font-weight: bold;
						margin-bottom: 10rpx;
						height: 40rpx;
						letter-spacing: 0.17px;
					}

					text:last-child {
						height: 34rpx;
						font-size: 12px;
						letter-spacing: 0.14px;
						color: rgba(64, 33, 16, 0.50);
					}
				}

				&>.time {
					position: absolute;
					top: 30rpx;
					right: 30rpx;
					font-size: 12px;
					color: #9B9B9B;
					letter-spacing: 0.14px;
				}

				&::before {
					content: "";
					position: absolute;
					width: 600rpx;
					height: 1px;
					background: #F2F2F2;
					right: 0rpx;
					bottom: 0;
				}
			}
		}

		.button-handle {
			display: flex;
			align-items: center;
			position: fixed;
			width: 100vw;
			height: 100rpx;
			background: #FFFFFF;
			bottom: 0rpx;

			&>view:first-child {
				width: 192rpx;
				display: flex;
				align-items: center;
				height: 100rpx;

				icon {
					margin-left: 30rpx;
					margin-right: 20rpx;
				}
			}

			&>.invitation-go {
				background: #FCC928;
				height: 100rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				flex: 1;

				&:active {
					opacity: 0.7;
				}
			}
		}
	}
</style>
